//
//  ChoosePhotoViewController.swift
//  LongTermInsurance
//
//  Created by zolobdz on 2018/12/8.
//  Copyright © 2018年 HeChao. All rights reserved.
//

import UIKit
import ObjectMapper
import AVKit
import AVFoundation
import TZImagePickerController

class ChoosePhotoViewController: UIViewController {
    static let imageWidth = (DeviceInfo.screenWidth.doubleValue() - 30*2 - 10*3)/4.0

    let maxImagePickerCount = 50

    lazy var pickerViewController = UIImagePickerController()


    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: ChoosePhotoViewController.imageWidth, height: ChoosePhotoViewController.imageWidth)
        layout.minimumInteritemSpacing = 10.0
        layout.minimumLineSpacing = 10.0
        layout.sectionInset = UIEdgeInsets.zero
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = CDColor.grayBackgroundColorA
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.register(PhotoPickerCollectionViewCell.self, forCellWithReuseIdentifier: "PhotoPickerCollectionViewCell")

        return collectionView
    }()
    
    
    lazy var imageArray: [ApplyPhotoModel] = {
        if let data = UserDefaults.standard.array(forKey: CDUserDefaultKey.userUploadPhotos) as? [[String: Any]]{
            let array = Mapper<ApplyPhotoModel>().mapArray(JSONArray: data)
            return array
        }
        return [ApplyPhotoModel]()
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = CDColor.grayBackgroundColorA
        title = "图片选择"

        // local
        setCustomView()
    }

    //MARK: Action

    @objc func rightBarButtonAction() {
        
        if imageArray.isEmpty {
            CDUtility.showMSG(message: "请先选择照片，再保存")
            return
        }

        let array = imageArray.compactMap { model -> NSDictionary? in
            var dict = [
                "name": model.name,
//                "data": model.data,
                "isRemote": model.isRemote,
                "uploaded": model.uploaded
                ] as [String : Any]
            if let data = model.data, !data.isEmpty {
                dict["data"] = data
            }
            return dict as NSDictionary
        }
        UserDefaults.standard.set(array, forKey: CDUserDefaultKey.userUploadPhotos)
        makeToast("选择成功")
        navigationController?.popViewController(animated: true)
    }
    
    func setCustomView(){
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(rightBarButtonAction))

        
        view.addSubview(collectionView)

        collectionView.snp.remakeConstraints { (maker) in
            maker.top.equalTo(0.0)
            maker.left.equalTo(15.0)
            maker.bottom.equalTo(-15.0)
            maker.right.equalTo(-15.0)
        }

        collectionView.reloadData()
    }

    //MARK: Private
    
    func takePhoto() {
        // 检测是否有拍照权限
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if (authStatus == .denied || authStatus == .restricted)
        {// 无相机权限 做一个友好的提示
            let alert = UIAlertController(title: "无法使用相机", message: "请在iPhone的'设置-隐私-相机'中允许访问相机", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "设置", style: .default, handler: { (action) in
                let url = URL(string: UIApplicationOpenSettingsURLString)
                if UIApplication.shared.canOpenURL(url!)
                {
                    UIApplication.shared.open(url!, options: [:], completionHandler: nil)
                }
            })
            let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alert.addAction(cancel)
            alert.addAction(okAction)
            self.present(alert, animated: true, completion: nil)
        }
        
        // 先保证相册权限，没有相册权限不能保存拍的照片
        if PHPhotoLibrary.authorizationStatus() == .authorized {
            // 请求权限
            AVCaptureDevice.requestAccess(for: AVMediaType.video) { [weak self](goodToGo) in
                DispatchQueue.main.async {
                    if let strongSelf = self
                    {
                        if goodToGo
                        {
                            let type = UIImagePickerControllerSourceType.camera
                            if UIImagePickerController.isSourceTypeAvailable(.camera)
                            {
                                strongSelf.pickerViewController.sourceType = type
                                strongSelf.pickerViewController.modalPresentationStyle = .currentContext
                                strongSelf.pickerViewController.delegate = strongSelf
                                strongSelf.present(strongSelf.pickerViewController, animated: true, completion: nil)
                            }
                        }
                    }
                }
            }
        } else if PHPhotoLibrary.authorizationStatus() == .notDetermined {
            // 正在弹框询问用户是否允许访问相册，监听权限状态
            // 请求权限
            PHPhotoLibrary.requestAuthorization({ (status) in
                if status != .authorized
                {
                    return
                }
                else
                {
                    self.takePhoto()
                }
            })
            return
        } else {
            // 已被拒绝，没有相册权限，将无法保存拍的照片
            let alert = UIAlertController(title: "无法使用相册", message: "请在iPhone的'设置-隐私-相册'中允许访问相机", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "设置", style: .default, handler: { (action) in
                let url = URL(string: UIApplicationOpenSettingsURLString)
                if UIApplication.shared.canOpenURL(url!)
                {
                    UIApplication.shared.open(url!, options: [:], completionHandler: nil)
                }
            })
            let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alert.addAction(cancel)
            alert.addAction(okAction)
            self.present(alert, animated: true, completion: nil)
            return
        }
        
        
        
    }
    
    func showPhotoPicker() {
        
        if maxImagePickerCount <= 0 {
            return
        }
        let count = maxImagePickerCount - imageArray.count
        let imagePickerVC = TZImagePickerController(maxImagesCount: count, columnNumber: 4, delegate: self, pushPhotoPickerVc: true)
        imagePickerVC?.cd_config()
        imagePickerVC?.allowPickingVideo = false
        imagePickerVC?.allowTakePicture = false
        imagePickerVC?.autoDismiss = false
        self.present((imagePickerVC)!, animated: true, completion: nil)
    }
    
    // 拍照上传
    func refreshCollectionViewWithAddedAsset(image: UIImage) {
        
        
        CDUtility.showHud()
//        let qnManager = QNUploadManager()
//        qnManager?.put(image.compressedData(),
//                       key: "upload/\(String.genrateUUID()).jpg",
//            token: qiniuToken,
//            complete: {[weak self] (responseInfo, key, resp) in
//                if let strongSelf = self{
//                    CDUtility.hidHud()
//                    if responseInfo?.statusCode == 200
//                    {
//                        strongSelf.photoDataArray.append((key!+",\(image.size.width)x\(image.size.height)",image))
//                        strongSelf.reloadPhotoCollection()
//                    }
//                    else if responseInfo?.statusCode == 401 // token 过期或者失效
//                    {
//                        strongSelf.makeToast("token过期请重新获取")
//                        strongSelf.getUserQiniuToken()
//                    }
//                    else
//                    {
//                        if let msg = responseInfo?.error.localizedDescription
//                        {
//                            strongSelf.makeToast(msg)
//                        }
//                    }
//                }
//            }, option: nil)
    }
    
}

extension ChoosePhotoViewController: UICollectionViewDataSource, UICollectionViewDelegate,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count == maxImagePickerCount ? maxImagePickerCount : imageArray.count+1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoPickerCollectionViewCell", for: indexPath)
        if let photoCell = cell as? PhotoPickerCollectionViewCell
        {
            if imageArray.count > indexPath.item
            {
                let model = imageArray[indexPath.item]
                photoCell.config(model)
            }
            else{
                photoCell.config()
            }
            
            photoCell.deleteImageBlock = {[weak self](data) in
                if let strongSelf = self
                {
                    for (index,model) in strongSelf.imageArray.enumerated() {
                        if model.name == data.name
                        {
                            strongSelf.imageArray.remove(at: index)
                            strongSelf.collectionView.reloadData()
                            break
                        }
                    }
                }
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let cell = collectionView.cellForItem(at: indexPath)
        if let photoCell = cell as? PhotoPickerCollectionViewCell
        {
            switch photoCell.photoFillState {
            case .blank:
//                self.showPhotoPicker()
                let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
                let action0 = UIAlertAction(title: "拍照", style: .default, handler: { (action) in
                    self.takePhoto()
                })

                let action1 = UIAlertAction(title: "去相册选择", style: .default, handler: { (action) in
                    self.showPhotoPicker()
                })

                let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)

                actionSheet.addAction(action0)
                actionSheet.addAction(action1)
                actionSheet.addAction(cancel)
                let popover = actionSheet.popoverPresentationController;
                if (popover != nil) {
                    popover?.sourceView = cell
                    popover?.sourceRect = cell!.bounds
                    popover?.permittedArrowDirections = UIPopoverArrowDirection.any
                }
                self.present(actionSheet, animated: true, completion: nil)
                
            default: break
            }
        }

        
    }
    
    
    //MARK: Photo
    
    func tz_imagePickerControllerDidCancel(_ picker: TZImagePickerController!) {
        picker.dismiss(animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }

    public func imagePickerController(_ picker: TZImagePickerController, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {

        picker.dismiss(animated: true, completion: nil)

        let chooseModelArray = photos.compactMap { (image0) -> ApplyPhotoModel? in
            let model = ApplyPhotoModel()
            model.name = "\(String.genrateUUID().prefix(12)).png"
            model.image = image0
            return model
        }
        imageArray.append(contentsOf: chooseModelArray)
        collectionView.reloadData()
    }
    
    // 拍照回调
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//        CDUtility.showHud()
        picker.dismiss(animated: true, completion: nil)

        let type = info[UIImagePickerControllerMediaType] as! NSString
        if type.isEqual(to: "public.image")
        {
//            let tzImagePickerVc = TZImagePickerController(maxImagesCount: 1, delegate: self)
//            tzImagePickerVc?.cd_config()
//            tzImagePickerVc?.showProgressHUD()
            let image = (info[UIImagePickerControllerOriginalImage] as! UIImage)
            let tempImage = TZImageManager.default().fixOrientation(image)

            let model = ApplyPhotoModel()
            model.name = "\(String.genrateUUID().prefix(12)).png"
            model.image = tempImage

            imageArray.append(model)
            collectionView.reloadData()

//            TZImageManager.default()!.savePhoto(with: image) { [weak self] (asset, error) in
//                if error != nil
//                {
//                    CDUtility.hidHud()
//                    tzImagePickerVc?.hideProgressHUD()
//                    // 失败
//                } else {
//                    TZImageManager.default()!.getCameraRollAlbum(false, allowPickingImage: true, needFetchAssets: false, completion: { (model) in
//
//                        TZImageManager.default()!.getAssetsFrom(model?.result, completion: {[weak self] (models) in
//                            // done
//                            tzImagePickerVc?.hideProgressHUD()
//                            var assetModel = models?.last
//                            if (tzImagePickerVc?.sortAscendingByModificationDate)!{
//                                assetModel = models?.first
//                            }
//
//                            if assetModel == nil {
//                                CDUtility.hidHud()
//                                return
//                            }
//
//                            let tempImage = TZImageManager.default().fixOrientation(image)
//                            CDUtility.hidHud()
//                            self!.refreshCollectionViewWithAddedAsset(image: tempImage!)
//
//                        })
//                    })
//                }
//            }
        }
    }

    
}
